package com.yuntoyun.fwcore.base;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.JsonObject;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yuntoyun.fwcore.appext.data.FwAppData;
import com.yuntoyun.fwcore.config.FwCodeConfig;
import com.yuntoyun.fwcore.model.FwResultBaseDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.plug.network.retrofit.FwRxApiManager;
import com.yuntoyun.fwcore.util.FwAlertDialogUtil;
import com.yuntoyun.fwcore.util.FwGsonUtil;
import com.yuntoyun.fwcore.util.FwMajorizationUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;

/**
 * 应用 ViewPager 组件 Fragment 基础类 (懒加载)
 */
public abstract class FwBaseViewPagerFragment extends Fragment implements View.OnClickListener {

    protected Activity fwActivity;
    protected View fwFragmentView;
    protected List<DisposableObserver> fwObserverList = new ArrayList<>();
    protected RxPermissions fwRxPermissions = null;
    protected LayoutInflater fwLayoutInflater;
    protected FwGsonUtil fwGsonUtil;

    /**
     * Fragment 懒加载相关设置
     */
    protected boolean isVisible = false;
    // 控件初始化完成标识
    private boolean isInitView = false;
    // 首次显示标识
    private boolean isVisiableFirst = true;

    protected Handler fwHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null == msg.obj)
                return;

            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            //+++++过滤错误提示 起始
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            if (msg.obj instanceof FwResultJsonDataModel) {
                FwResultJsonDataModel model = (FwResultJsonDataModel) msg.obj;
                if (null == model) {
                    return;
                }
                if (FwCodeConfig.CODE_LOGIN_AGAIN == model.getFwStatus()) {
                    FwAppData.clearLoginData();
//                    FwIntentUtil.builder().startActivity(fwActivity, LoginActivity.class, null,
//                            new int[]{
//                                    Intent.FLAG_ACTIVITY_CLEAR_TOP
//                            });
//                    //发送广播
//                    Intent intent = new Intent();
//                    intent.setAction(MainActivity.ACTION_APP_EXIT);
//                    fwActivity.sendBroadcast(intent, MainActivity.PERMISSION_APP_EXIT);
                    FwToastUtil.builder().makeText("账号已在其他设备登录，请重新登录！");
                    return;
                }
                if (FwCodeConfig.CODE_SUCCESSED != model.getFwStatus()) {
                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "提示", model
                            .getFwMessage());
                    return;
                }
                model.setIndex(msg.what);
                messageHandler(model);
            } else if (msg.obj instanceof FwResultJsonListDataModel) {
                FwResultJsonListDataModel model = (FwResultJsonListDataModel) msg.obj;
                if (null == model) {
                    return;
                }

                if (FwCodeConfig.CODE_LOGIN_AGAIN == model.getFwStatus()) {
                    FwAppData.clearLoginData();
//                    FwIntentUtil.builder().startActivity(fwActivity, LoginActivity.class, null,
//                            new int[]{
//                                    Intent.FLAG_ACTIVITY_CLEAR_TOP
//                            });
//                    //发送广播
//                    Intent intent = new Intent();
//                    intent.setAction(MainActivity.ACTION_APP_EXIT);
//                    fwActivity.sendBroadcast(intent, MainActivity.PERMISSION_APP_EXIT);
                    FwToastUtil.builder().makeText("账号已在其他设备登录，请重新登录！");
                    return;
                }

                if (FwCodeConfig.CODE_SUCCESSED != model.getFwStatus()) {
                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "提示", model
                            .getFwMessage());
                    return;
                }
                model.setIndex(msg.what);
                messageHandler(model);
            } else {
                messageHandler(msg);
            }
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            //+++++过滤错误提示 结束
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (null == fwFragmentView || isAgainCreateView()) {
            fwActivity = getActivity();
            fwLayoutInflater = LayoutInflater.from(fwActivity);
            fwFragmentView = inflater.inflate(getLayoutResId(), container, false);
            ButterKnife.bind(this, fwFragmentView);
            this.isInitView = true;
            //工具类
            fwGsonUtil = FwGsonUtil.builder();
            //抽象方法
            if (this.isVisible) {
                this.isVisiableFirst = false;
                initNavigation();
                initView(fwFragmentView);
                initEvent();
                initData();
            }
        } else {
            ViewGroup parent = (ViewGroup) fwFragmentView.getParent();
            if (parent != null) {
                parent.removeView(fwFragmentView);
            }
        }
        return fwFragmentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        //必须在Fragment附加到Activity后方可实例化
        fwRxPermissions = new RxPermissions(this);
    }

    //仅在FragmentPagerAdapter中会运行
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //FragmentPagerAdapter在fragment切换时被调用，如果是切换到当前页，那么isVisibleToUser==true，否则为false
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
            if (isVisiableFirst) {
                if (isInitView) {
                    this.isVisiableFirst = false;
                    initNavigation();
                    initView(fwFragmentView);
                    initEvent();
                    initData();
                }
            }
        } else {

        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    protected void doPostData(int what, Observable<FwResultJsonDataModel> observable, boolean
            showloading) {
        FwOkHttp.instance().doPost(fwActivity, fwHandler.obtainMessage(what), observable,
                fwObserverList,
                showloading);
    }

    protected void doPostListData(int what, Observable<FwResultJsonListDataModel> observable,
                                  boolean showloading) {
        FwOkHttp.instance().doPost(fwActivity, fwHandler.obtainMessage(what), observable,
                fwObserverList,
                showloading);
    }

    protected void doPostBaseData(int what, Observable<FwResultBaseDataModel<JsonObject>>
            observable, boolean
                                          showloading) {
        FwOkHttp.instance().doPost(fwActivity, fwHandler.obtainMessage(what), observable,
                fwObserverList,
                showloading);
    }

    protected abstract boolean isAgainCreateView();

    protected abstract int getLayoutResId();

    protected abstract void initView(View layoutView);

    protected abstract void initData();

    protected abstract void initEvent();

    protected abstract void initNavigation();

    protected abstract void messageHandler(Message msg);

    protected abstract void messageHandler(FwResultJsonDataModel model);

    protected abstract void messageHandler(FwResultJsonListDataModel model);

    @Override
    public void onDestroyView() {
        FwRxApiManager.init().cancelAll(fwObserverList);
        super.onDestroyView();
    }

    /**
     * 检测快速点击
     *
     * @return
     */
    protected boolean isFastClick() {
        boolean isFast = FwMajorizationUtil.builder().isFastClick();
        if (isFast) {
            FwToastUtil.builder().makeText("禁止快速重复点击！");
        }
        return isFast;
    }
}
